﻿using System.Collections.Generic;
using System.Linq;

namespace CRMS.Models
{
    public class DepartmentRep
    {
        private StoreDBDataContext storeDB = new StoreDBDataContext();

        //
        //Query Methods
        /// <summary>
        /// 获取所有的院系
        /// </summary>
        /// <returns>返回院系集合</returns>
        public IQueryable<Department> GetDepartments()
        {
            return from dp in storeDB.Departments select dp;
        }
        /// <summary>
        /// 通过给定ID获取特定的院系
        /// </summary>
        /// <param name="id">院系参数ID</param>
        /// <returns>返回院系对象</returns>
        public Department GetDeptByID(string id)
        {
            return storeDB.Departments.SingleOrDefault(d => d.DepartmentId == id);
        }
        /// <summary>
        /// 通过给定Name获取特定院系
        /// </summary>
        /// <param name="name">院系参数Name</param>
        /// <returns>返回院系对象</returns>
        public Department GetDeptByName(string name)
        {
            return storeDB.Departments.SingleOrDefault(d => d.DepartmentName == name);
        }
        //通过学院名称获取学院ID
        public string getDepartIdByDName(string dname)
        {
            if (storeDB.Departments.SingleOrDefault(d => d.DepartmentName == dname) != null)
            {
                return storeDB.Departments.SingleOrDefault(d => d.DepartmentName == dname).DepartmentId;
            }
            else
            {
                return null;
            }
        }

        //
        //Insert/Delete
        /// <summary>
        /// 向数据库院系表添加一条院系记录
        /// </summary>
        /// <param name="dept">院系实体</param>
        public void Add(Department dept)
        {
            storeDB.Departments.InsertOnSubmit(dept);
        }
        /// <summary>
        /// 从数据库院系表删除一条院系记录
        /// </summary>
        /// <param name="dept">院系实体参数</param>
        public void Delete(Department dept)
        {
            //先删除关联表
            storeDB.Students.DeleteAllOnSubmit(dept.Students);
            storeDB.Courses.DeleteAllOnSubmit(dept.Courses);
            storeDB.Teachers.DeleteAllOnSubmit(dept.Teachers);

            storeDB.Departments.DeleteOnSubmit(dept);
        }

        //
        //Persistence
        /// <summary>
        /// 把更改保存到数据库
        /// </summary>
        public void Save()
        {
            storeDB.SubmitChanges();
        }
    }
}
